package cg.studio.distribute.vote.site;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import cg.studio.distribute.vote.model.Topic;
import cg.studio.distribute.vote.server.VoteManager;

/**
 * The site will synchronize with the server in a certain period
 * The site will keep the vote in certain period
 * 
 * @author Bright Chen
 *
 */
public class TypicalSite implements Site
{
  private volatile int[] totalVote = new int[ Topic.values().length ];
  private volatile int[] periodVote = new int[ Topic.values().length ];
  
  private ReadWriteLock totalVoteLock = new ReentrantReadWriteLock();
  private ReadWriteLock periodVoteLock = new ReentrantReadWriteLock();
  
  public void vote( Topic topic )
  {
    periodVote[ topic.ordinal()-1 ]++;
  }

  public int[] getTopicVote()
  {
    return totalVote;
  }

  //send period vote to the server, let server trigger this function
  public int[] getPeriodVote()
  {
    periodVoteLock.readLock().lock();
    
    final int topicCount = Topic.values().length;
    int[] periodVoteCopy = new int[ topicCount ];
    for( int i=0; i<topicCount; ++i )
    {
      periodVoteCopy[i] = periodVote[i];
    }
    
    periodVoteLock.readLock().unlock();
    
    return periodVoteCopy;
  }
  
  //get total vote from server and keep it
  public void syncTotalVote()
  {
    int[] voteFromServer = VoteManager.getServer().getTotalVote();
    
    totalVoteLock.writeLock().lock();
    for( int i=0; i<voteFromServer.length; ++i )
    {
      totalVote[i] = voteFromServer[i];
    }
    totalVoteLock.writeLock().lock();
  }
}
